﻿#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QStateMachine>
#include <QPropertyAnimation>
#include <QEventTransition>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /// 状态机
    QStateMachine *machine = new QStateMachine(this);

    /// 状态 1
    QState *s1 = new QState();

    /// 状态 1 下 stateLabel及 pushButton 的属性
    s1->assignProperty(ui->stateLabel, "text", "Current state: 1");
    s1->assignProperty(ui->pushButton, "geometry", QRect(50, 200, 100, 50));

    /// 状态 2
    QState *s2 = new QState();

    /// 状态 2 下 stateLabel及 pushButton 的属性
    s2->assignProperty(ui->stateLabel, "text", "Current state: 2");
    s2->assignProperty(ui->pushButton, "geometry", QRect(200, 50, 140, 100));

    /// 状态转换事件
    /// ui->changeState, QEvent::MouseButtonPress 指明当 changeState 按钮
    /// 被按下时触发状态转换事件
    QEventTransition *t1 = new QEventTransition(ui->changeState, QEvent::MouseButtonPress);

    /// 状态转换的目标为 s2
    t1->setTargetState(s2);

    /// 添加状态转换时的动画
    QPropertyAnimation* animation = new QPropertyAnimation(ui->pushButton, "geometry");
    animation->setEasingCurve(QEasingCurve::OutBounce);
    animation->setDuration(3000);

    t1->addAnimation(animation);

    /// 将状态转换事件关联到 s1 状态
    /// 即在 s1 状态下，changeState 按钮被按下时，转换状态到 s2
    s1->addTransition(t1);

    /// 逻辑同上
    QEventTransition *t2 = new QEventTransition(ui->changeState, QEvent::MouseButtonPress);
    t2->setTargetState(s1);
    t2->addAnimation(animation);
    s2->addTransition(t2);

    /// 添加状态到状态机中
    machine->addState(s1);
    machine->addState(s2);

    /// 设置初始状态
    machine->setInitialState(s1);

    /// 启动状态机
    machine->start();
}

MainWindow::~MainWindow()
{
    delete ui;
}
